package com.feng.gameproj;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;

public class GameSurface extends SurfaceView implements Runnable, Callback 
{
	private boolean loopCtrl = false;
	
	private SurfaceHolder holder = null;
	private int count = 0;
	public int y = 50;

	public GameSurface(Context context) 
	{
		super(context);
		
		this.holder = this.getHolder();
		this.holder.addCallback(this);
		
		this.setFocusable(true);
		this.loopCtrl = true;
	}

	@Override
	public void run() 
	{
		while (this.loopCtrl)
		{
			try 
			{
				Thread.sleep(500);
			}
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
			synchronized (this.holder)
			{
				this.drawing();
			}
		}
	}

	public void drawing ()
	{
		Canvas canvas = null;
		if (this.holder != null)
			canvas = this.holder.lockCanvas();
		if (canvas == null)
			return;
		
		if (this.count < 100)
		{
			count ++;
		}
		else
		{
			count = 0;
		}
		
		Paint paint = new Paint ();
		// 绘制黑色矩形 -- 用于清屏
		paint.setAntiAlias(true);
		paint.setColor(Color.BLACK);
		canvas.drawRect(0, 0, 320, 480, paint);
		
		switch (this.count % 4)
		{
			case 0:
				paint.setColor(Color.BLUE);
				break;
			case 1:
				paint.setColor(Color.GREEN);
				break;
			case 2:
				paint.setColor(Color.RED);
				break;
			case 3:
				paint.setColor(Color.YELLOW);
				break;
			default:
				paint.setColor(Color.WHITE);
				break;
		}
		canvas.drawCircle ((320-25)/2, y, 50, paint);
		this.holder.unlockCanvasAndPost(canvas);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {}

	@Override
	public void surfaceCreated(SurfaceHolder holder) 
	{
		new Thread(this).start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) 
	{
		this.loopCtrl = false;
	}

}
